package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.JSONException;

/**
 *
 * @Title: ApiBPQueryWO* @Description:深圳宝安排水小程序查询案件历史接口--外部接口
 * @author: chieh* @date 2020-11-11 21:28:00
 *
 */
public class ApiBPQueryWO implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPQueryWO.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        log.debug("-------------------------start ApiBPQueryWO 开始-----------------");

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String reJson = null;
        long endTime = 0;

        //获取参数openid
        def openid = request.getParameter("openid");
        String pagenum = request.getParameter("pagenum");//当前页
        String pagesize = request.getParameter("pagesize");//每页大小
        log.debug("解析信息-openid：" + openid + "	pagenum" + pagenum + "	pagesize" + pagesize);

        String rec_guid = "";
        String companytpye = "";
        String business1 = "";
        String business2 = "";
        String business3 = "";
        String isstreet = "";
        String address = "";
        String description = "";
        String locationx = "";
        String locationy = "";
        String status = "";
        String handleresult = "";
        String url = "";
        String filename = "";
        String deal_staff = "";
        String deal_time = "";

        JSONArray resArray = new JSONArray();
        JSONObject resObject = new JSONObject();

        try {
            if (openid == null || openid == "") {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(phone必填字段;),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }

            String selectSQL = "select CUSTOMER_GUID from CUSTOMER  where wechatid=? ORDER BY CREATEDDATE asc";
            List<Map<String, Object>> customerresult = jt.queryForList(selectSQL, openid);
            log.debug("查看客户是否存在sql结果:" + customerresult.toString());

            String old_customer_guid = null;
            if (customerresult.size() > 0) {
                old_customer_guid = customerresult.get(0).get("CUSTOMER_GUID");
                log.debug("old_customer_guid" + old_customer_guid);

                int pagenumn = (Integer.parseInt(pagenum) - 1) * Integer.parseInt(pagesize);

                String selectSQL2 = "select rec_guid AS objective_guid from wx_uploads_list r1 left join customer r2 on r1.open_id = r2.wechatid where r1.open_id = ? order by r1.Create_Time Desc limit " + pagenumn + "," + pagesize;
                List<Map<String, Object>> listcountresult = jt.queryForList(selectSQL2, openid);

                int count = listcountresult.size();
                if (count > 0) {
                    log.debug("历史案件存在一个以上！" + count);
                    for (int i = 0; i < count; i++) {
                        String objective_guid = listcountresult.get(i).get("objective_guid");
                        log.debug("objective_guid:" + objective_guid);

                        String selectSQL3 = '''Select R1.Rec_Guid,
                                               R1.Open_Id,
                                               R1.Level_Id1 As Companytpye,
                                               r3.Code_Name As Business1,
                                               r4.Code_Name As Business2,
                                               R1.Level_Id4 As Business3,
                                               R1.Level_Id5 As Isstreet,
                                               R1.Level_Id6 As Address,
                                               R1.Comments As Description,
                                               Ifnull(R1.Locationx, '') As Locationx,
                                               Ifnull(R1.Locationy, '') As Locationy,
                                               R1.Upload_Arr,
                                               Date_Format(R1.Create_Time, '%Y-%m-%d %H:%i:%s') As Create_Time,
                                               Date_Format(R1.Deal_Time, '%Y-%m-%d %H:%i:%s') As Deal_Time,
                                               R6.Staffname As Deal_Staff,
                                               R5.Code_Name As Status,
                                               R1.Deal_Comments As Handleresult
                                          From Wx_Uploads_List R1
                                          Left Join Customer R2
                                            On R1.Open_Id = R2.Wechatid
                                          Left Join c_Codetables_Wxm R3
                                            On R1.Level_Id2 = R3.Code_Id
                                           And R3.Use_Type = 'B0001'
                                          Left Join c_Codetables_Wxm R4
                                            On R1.Level_Id3 = R4.Code_Id
                                           And R4.Use_Type = 'B0002'
                                          Left Join c_Codetables R5
                                            On R1.Deal_Status = R5.Code_Id
                                           And R5.Use_Type = 'WX_DEALSTATUS'
                                          Left Join Staff R6
                                            On R1.Deal_Staff_Id = R6.Staff_Id
                                             Where R1.Rec_Guid = ?''';
                        List<Map<String, Object>> listresult = jt.queryForList(selectSQL3, objective_guid);
                        log.debug("SQL获取数据:" + listresult);

                        if (listresult.size() > 0) {
                            rec_guid = listresult.get(0).get("Rec_Guid");
                            companytpye = listresult.get(0).get("Companytpye");
                            business1 = listresult.get(0).get("Business1");
                            business2 = listresult.get(0).get("Business2");
                            business3 = listresult.get(0).get("Business3");
                            isstreet = listresult.get(0).get("Isstreet");
                            address = listresult.get(0).get("Address");
                            description = listresult.get(0).get("Description");
                            locationx = listresult.get(0).get("Locationx");
                            locationy = listresult.get(0).get("Locationy");
                            String upload_arr = listresult.get(0).get("Upload_Arr");

                            status = listresult.get(0).get("Status");
                            deal_staff = listresult.get(0).get("Deal_Staff");
                            deal_time = listresult.get(0).get("Deal_Time");
                            handleresult = listresult.get(0).get("Handleresult");

                            List urlresult = new ArrayList();
                            urlresult = upload_arr.split(";");

                            //获取总行数
                            def urllistsize = urlresult.size();
                            log.debug("sql获取总条数:" + urllistsize);
                            JSONArray urlresArray = new JSONArray();
                            JSONArray urlstrArray = new JSONArray();
                            JSONObject urlresObject = new JSONObject();
                            String urlpath = "";
                            for (int m = 0; m < urllistsize; m++) {
                                urlpath = urlresult.get(m);
                                log.debug("urlpath:" + urlpath);
                                if (urlpath == null) {
                                    urlpath = "";
                                }

                                urlresObject.put("url", urlpath);
                                urlresArray.add(urlresObject);

                                urlstrArray.add(urlpath);
                            }
                            log.debug("urlresArray：" + urlresArray);

                            resObject.put("rec_guid", rec_guid);
                            resObject.put("companytpye", companytpye);
                            resObject.put("business1", business1);
                            resObject.put("business2", business2);
                            resObject.put("business3", business3);
                            resObject.put("isstreet", isstreet);
                            resObject.put("address", address);
                            resObject.put("description", description);
                            resObject.put("locationx", locationx);
                            resObject.put("locationy", locationy);
                            resObject.put("status", status);
                            resObject.put("deal_staff", deal_staff);
                            resObject.put("deal_time", deal_time);
                            resObject.put("handleresult", handleresult);
                            resObject.put("arr", urlresArray);
                            resObject.put("urlarr", urlstrArray);
                            log.debug("resObject：" + resObject.toString());

                            resArray.add(resObject);
                        }
                    }
                    endTime = System.currentTimeMillis();
                    reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功,调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[" + resArray.toString() + "]}";
                } else {
                    endTime = System.currentTimeMillis();
                    reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功(无客户相关案件),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;
                }
            } else {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功(无客户相关案件),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"查询接口调用处理,请检查确认入参有效且合法\",\"data\":[]}";

        }
        return reJson;

    }
}